package com.dongdongshop.service.impl;

import com.dongdongshop.mapper.TbSellerMapper;
import com.dongdongshop.model.TbSeller;
import com.dongdongshop.service.SellerService;
import com.dongdongshop.util.ShiroUtils;
import com.dongdongshop.vo.SellerVO;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class SellerServiceImpl implements SellerService {
    @Resource
    private TbSellerMapper sellerMapper;

    @Override
    public SellerVO getSellerByName(String sellerId) {
        TbSeller tbSeller = sellerMapper.selectByPrimaryKey(sellerId);
        if (tbSeller == null) {
            return null;
        }
        SellerVO vo = new SellerVO();
        BeanUtils.copyProperties(tbSeller, vo);
        return vo;
    }

    @Override
    public int registerSeller(SellerVO sellerVO) {
        TbSeller seller = new TbSeller();
        BeanUtils.copyProperties(sellerVO, seller);
        String salt = ShiroUtils.generateSalt(6);
        String password = ShiroUtils.encryptPassword("MD5", seller.getPassword(), salt, 3);
        seller.setSalt(salt);
        seller.setPassword(password);
        seller.setStatus("0");
        int i = sellerMapper.insertSelective(seller);
        return i;
    }

    @Override
    public List<SellerVO> getAllSeller() {
        List<TbSeller> tbSellers = sellerMapper.selectByExample(null);
        List<SellerVO> collect = tbSellers.stream().map(seller -> {
            SellerVO vo = new SellerVO();
            BeanUtils.copyProperties(seller, vo);
            return vo;
        }).collect(Collectors.toList());
        return collect;
    }

    @Override
    public SellerVO getSellerById(String sellerId) {
        TbSeller seller = sellerMapper.selectByPrimaryKey(sellerId);
        SellerVO vo = new SellerVO();
        BeanUtils.copyProperties(seller, vo);
        return vo;
    }

    @Override
    public void updateSellerById(String sellerId) {
        TbSeller seller = sellerMapper.selectByPrimaryKey(sellerId);
        seller.setStatus("1");
        sellerMapper.updateByPrimaryKeySelective(seller);
    }
}
